package com.nuanshui.heatedloan.web;

import com.alibaba.dubbo.config.annotation.Reference;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.entity.cms.security.Module;
import com.nuanshui.heatedloan.entity.cms.security.User;
import com.nuanshui.heatedloan.entity.cms.security.UserRole;
import com.nuanshui.heatedloan.service.cms.security.AdminUserService;
import com.nuanshui.heatedloan.service.cms.security.FrontUserService;
import com.nuanshui.heatedloan.service.cms.security.ModuleService;
import com.nuanshui.heatedloan.service.cms.security.UserRoleService;
import com.nuanshui.heatedloan.userinfo.facade.UserQueryService;
import com.nuanshui.heatedloan.util.SecurityConstants;
import com.nuanshui.heatedloan.util.UserUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Index控制器
 */
@Controller
@RequestMapping("")
public class ApiIndexController extends ApiController implements InitializingBean {

	@Autowired
	private AdminUserService userService;

	@Autowired
	private UserRoleService userRoleService;

	@Autowired
	private ModuleService moduleService;

	@Autowired
	private FrontUserService frontUserService;

	@Reference(url= GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserQueryService userQueryService;
	
	/**
	 * 进入首页
	 * 
	 * @param request
	 * @return
	 */
	//@RequiresAuthentication
	@RequestMapping(value = "/cms/manage/index", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String index(final HttpServletRequest request) {

		// User user = userService.get(shiroUser.getLoginName());
		// 1、设置用户角色
		final List<UserRole> userRoles = userRoleService.find(UserUtil
				.getCurrentUserId());
		for (UserRole item:userRoles) {
			item.getRole().setNeedPermission(true);
		}

		UserUtil.getCurrentUser().setUserRoles(userRoles);

		final Module menuModule = getMenuModule(userRoles);

		// 2、在session中放入user
		request.getSession().setAttribute(SecurityConstants.LOGIN_USER,
				UserUtil.getCurrentUser());
		// 放入用户有权限查看的模块
	//	request.setAttribute("menuModule", menuModule);
		// 放置系统公告
		return  success(  menuModule );
	}

	/**
	 * 返回用户有权限查看的模块
	 * 
	 * @param userRoles
	 * @return 返回用户有权限查看的模块的根节点
	 */
	private Module getMenuModule(final List<UserRole> userRoles) {
		// 1、得到当前用户的所有权限
		final Set<String> permissionSet = Sets.newHashSet();
		for (final UserRole userRole : userRoles) {
			final Set<String> tmp = Sets.newHashSet(userRole.getRole()
					.getPermissionList());
			permissionSet.addAll(tmp);
		}
		// 2、组装菜单,只获取二级菜单，再多的话就需要递归了
		final Module rootModule = moduleService.getTree();// 拿到所有的模块
		final List<Module> list1 = Lists.newArrayList();// 用于装一级菜单
		for (final Module m1 : rootModule.getChildren()) {
			// 只加入拥有view权限的Module
			// 假如这个大模块有view的权限，再看看里面的小模块有没有view权限
			if (permissionSet.contains(m1.getSn() + ":"
					+ SecurityConstants.OPERATION_VIEW)) {
				final List<Module> list2 = Lists.newArrayList();// 用于装二级菜单
				for (final Module m2 : m1.getChildren()) {// 遍历下面的二级菜单
					if (permissionSet.contains(m2.getSn() + ":"
							+ SecurityConstants.OPERATION_VIEW)) {
						list2.add(m2);
					}
				}
				m1.setChildren(list2);// 把二级菜单放在一级菜单中
				list1.add(m1);// 将符合条件的一级菜单放好
			}
		}
		rootModule.setChildren(list1);// list1中都是符合条件的一级菜单

		return rootModule;
	}
	
	@RequestMapping(value = "/updatePwd")
	public String updatePassword(final HttpServletRequest request,final String oldPassword, final String plainPassword, final String rPassword) {
		final User user = (User) request.getSession().getAttribute(SecurityConstants.LOGIN_USER);

		// 两次输入的密码一样
		if (plainPassword.equals(rPassword)) {
			user.setPlainPassword(plainPassword);
			
			//判断当前用户是不是app端用户
			Integer frontUserId = userService.loadFrontUserIdByAdminUserId(user.getId());
			if(frontUserId == null){
				userService.update(user);
			}else{
				frontUserService.updatePassWord(frontUserId, plainPassword);
			}
			return success();
		}

		return fail("密码修改失败！");
	}

	@Override
	public void afterPropertiesSet() throws Exception {

	}


	/*//**
	 * 跳转到修改用户信息的界面
	 *//*
	@RequestMapping(value = "/updateBase", method = RequestMethod.GET)
	public String preUpdate() {
		return "cms/index/updateBase";
	}

	*//**
	 * 修改用户信息
	 * 
	 * @return
	 *//*
	@RequestMapping(value = "/updateBase", method = RequestMethod.POST)
	@ResponseBody
	public String update(final User user, final HttpServletRequest request,
			final MultipartFile photos) {
		final User loginUser = (User) request.getSession().getAttribute(
				SecurityConstants.LOGIN_USER);
		loginUser.setPhone(user.getPhone());
		loginUser.setEmail(user.getEmail());
		userService.update(loginUser, photos);
		final AjaxObject ajaxObject = new AjaxObject("详细信息修改成功！");
		return ajaxObject.toString();
	}*/
}
